#include <REGX52.H>
#include <INTRINS.H>
#include "IR.h"
#include "Timer0.h"
#include "Int0.h"
#include "LCD1602.h"

unsigned int IR_Time0;
unsigned char IR_State;
unsigned char IR_CommendFlag;
unsigned char IR_RepeatFlag;
unsigned char IR_Data[4];
unsigned char IR_P;
unsigned char IR_Address;
unsigned char IR_Commend;



void IR_Init(void)
{
	Timer0_Init();
	Int0_Init();
}

unsigned char IR_GetCommendFlag(void)
{
	if(IR_CommendFlag)
	{
		IR_CommendFlag = 0;
		return 1;
	}
	
	return 0;
}

unsigned char IR_GetRepeatFlag(void)
{
	if(IR_RepeatFlag)
	{
		IR_RepeatFlag = 0;
		return 1;
	}
	
	return 0;
}

unsigned char IR_GetCommend(void)
{
	return IR_Commend;
}

unsigned char IR_GetAddress(void)
{
	return IR_Address;
}

/**
  * @brief  外部中断0中断服务函数中处理红外遥控器触发下降沿中断
  * @param  无
  * @retval 无
  */
void Int0_Routine(void) interrupt 0
{
	/*
	  IR_State:0, 空闲状态
	  IR_State:1，搜寻状态，搜寻Start起始条件或者Repeat条件
	  IR_State:2，数据接收状态
	 */
	
	if(IR_State == 0)				//状态机0空闲状态，收到下降沿中断转移到1状态
	{
		Timer0_Stop();
		Timer0_SetCounter(0);
		Timer0_Run();
		IR_State = 1;

	}
	else if(IR_State == 1)			//状态机1空闲状态，再次收到下降沿检查时起始条件或者Repeat条件
	{
		IR_Time0 = Timer0_GetCounter();
		Timer0_SetCounter(0);
		
		//12100<= x && x<=12900
		if((IR_Time0 <= 12500+400) && (IR_Time0 >= 12500-400)){			//起始条件，跳转到2状态
			IR_State = 2;
			//P1_0 = 0;
			//P1_0 = 1;
		}
		//10068<= x && x<=10768
		else if((IR_Time0 <= 10368+400) && (IR_Time0 >= 10368-400)){	//Repeat条件，跳转到0状态
			IR_RepeatFlag = 1;
			IR_State = 0;
		}
		else{															//错误处理，，跳转到1状态
			IR_State = 1;
		}
	}
	else if(IR_State == 2)		//状态机2状态，等待下降沿读取数据
	{
		IR_Time0 = Timer0_GetCounter();
		Timer0_SetCounter(0);
		
		if((IR_Time0 <= 1037+300) && (IR_Time0 >= 1037-300)){
			IR_Data[IR_P/8] &= ~(0x01 << (IR_P%8));
			IR_P++;
		}
		else if((IR_Time0 <= 2083+300) && (IR_Time0 >= 2083-300)){
			IR_Data[IR_P/8] |= (0x01 << (IR_P%8));
			IR_P++;
		}
		else{
			IR_State = 1;
			IR_P = 0;
		}
		
		if(IR_P >= 32)
		{
			IR_P = 0;
			
			if(IR_Data[0] == ~IR_Data[1] && IR_Data[2] == ~IR_Data[3]){
				IR_CommendFlag = 1;
				IR_State = 0;
				IR_Address = IR_Data[0];
				IR_Commend = IR_Data[2];
			}
			else{
				IR_State = 1;
			}
		}
	}
}

